import find from 'lodash.find';
import { TaskAPI } from '@/services';
import { onMounted, onUnmounted, watch } from 'vue';
import { ETB_URL } from '@/common/constants';

export default function useStatisticsViewerMessenger(etb, statisticalWidget, viewerFrame) {
  const fetchOperations = async () => {
    if (!statisticalWidget.value) return;
    const widgetIds = statisticalWidget.value.widgets.map(w => w.itemId);
    const { data: operations } = await TaskAPI.listOperations(
      { filter: { page: etb.pageNumber, widget_ids: widgetIds, data_type: 'interact' } }
    );
    const pageOperations = {}; 
    operations.forEach((op) => {
      try {
        if (!pageOperations[op.creator_id]) pageOperations[op.creator_id] = [];
        pageOperations[op.creator_id].push({
          user: { id: op.creator_id, name: op.creator_name },
          widgetId: op.widget_id,
          content: typeof op.data === "string" ? JSON.parse(op.data) : op.data,
          created_at: op.created_at,
        });
      } catch (e) {
        console.error(e);
      }
    });
    viewerFrame.value.contentWindow.postMessage({
      type: 'renderData',
      data: {
        results: JSON.stringify(Object.keys(pageOperations).map(k => pageOperations[k]))
      }
    }, '*');
    etb.pageOperations = operations;
  };

  const renderStatistics = async () => {
    if (viewerFrame.value && statisticalWidget.value) {
      const { itemId: widgetId } = statisticalWidget.value.widgets[0];
      const pageWidget = find(etb.pageWidgets, { itemId: widgetId }); // 包含model内容
      const students = await TaskAPI.listStudents();
      const message = {
        type: 'renderData',
        data: {
          bookDir: `${ETB_URL}/OEBPS/`,
          widgetId,
          model: pageWidget && JSON.stringify(pageWidget.model),
          students: JSON.stringify(students),
        }
      };
      if (statisticalWidget.value.isGrouped) {
        message.data.isGrouped = true;
        message.data.groupName = statisticalWidget.value.groupName;
        message.data.widgets = JSON.stringify(statisticalWidget.value.widgets.map((w) => {
          const pageWidget = find(etb.pageWidgets, { itemId: w.itemId });
          return {
            itemId: w.itemId,
            displayName: w.displayName,
            model: pageWidget && pageWidget.model,
          }
        }));
      }
      viewerFrame.value.contentWindow.postMessage(message, '*');
      await fetchOperations();
    }
  };

  const handleMessage = (e) => {
    const { type } = e.data;
    switch(type) {
      case 'statisticsViewer:created':
        renderStatistics();
        break;
      default:
        break;
    }
  };

  onMounted(() => window.addEventListener('message', handleMessage));
  onUnmounted(() => window.removeEventListener('message', handleMessage));
  watch(statisticalWidget, renderStatistics);

  return {
    fetchOperations,
  };
}